﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using N_m3u8DL_RE_easydown.Dtos;
using N_m3u8DL_RE_easydown.Entities;
using System.Collections.Concurrent;

namespace N_m3u8DL_RE_easydown.Controllers
{
    public class TasksController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IMemoryCache _cache;
        private readonly ConcurrentDictionary<Guid, TaskEntity> _tasks;

        public TasksController(ILogger<HomeController> logger, IMemoryCache cache, ConcurrentDictionary<Guid, TaskEntity> tasks)
        {
            _logger = logger;
            _cache = cache;
            _tasks = tasks;
        }

        public IActionResult Index()
        {
            List<TaskGroupDto>? taskGroups = [];
            List<UrlTaskDto>? tasksDto = [];
            foreach (var task in _tasks)
            {
                tasksDto.Clear();
                foreach (var downTask in task.Value.Urls)
                {
                    string? pr = string.Empty;
                    if (!_cache.TryGetValue($"{downTask.Guid}", out pr))
                    {
                    }
                    if (string.IsNullOrWhiteSpace(pr))
                    {
                        pr = "00.00";
                    }
                    if (!double.TryParse(pr, out var _pr))
                    {
                        continue;
                    }
                    tasksDto.Add(new UrlTaskDto
                    {
                        Num = downTask.Num,
                        Url = downTask.Url,
                        Percentage = _pr
                    });
                }
                taskGroups.Add(new TaskGroupDto
                {
                    Guid = task.Key,
                    Percentage = tasksDto.Count <= 0 ? 0 : tasksDto.Sum(x => x.Percentage) * 0.01 / tasksDto.Count,
                    Name = task.Value.Name,
                    Tasks = tasksDto
                });
            }
            ViewData["Tasks"] = taskGroups;
            return View();
        }
    }
}
